package prickworlds.gui;

import java.util.ArrayList;

import prickworlds.structure.KeyEvent;
import prickworlds.structure.MouseEvent;

/**
 * base class for a container that contents various {@link Control}s
 * 
 * @author Faruk Acibal, Richard Dziambor, Christian Holzreuter, Nicolas Winkler
 * 
 */
public class Frame extends Control {
	/**
	 * the list of the {@link Control}s
	 */
	ArrayList<Control> controls;

	/**
	 * {@link FocusDealer} that handles focus requests of the children
	 * {@link Control}s
	 */
	FocusDealer focusDealer;

	/**
	 * default constructor
	 */
	public Frame() {
		controls = new ArrayList<Control>();
		focusDealer = new FocusDealer();
	}

	/**
	 * adds a new {@link Control} to the frame
	 * 
	 * @param control
	 *            the {@link Control} to add
	 */
	public void add(Control control) {
		controls.add(control);
		if (control instanceof ActiveControl) {
			ActiveControl ac = (ActiveControl) control;
			focusDealer.add(ac.focus);
		}
	}

	/**
	 * removes a {@link Control} to the frame
	 * 
	 * @param control
	 *            the {@link Control} to remove
	 */
	public void remove(Control control) {
		controls.remove(control);
		if (control instanceof ActiveControl) {
			ActiveControl ac = (ActiveControl) control;
			focusDealer.remove(ac.focus);
		}
	}

	@Override
	public void update() {
		for (int i = 0; i < controls.size(); i++) {
			Control control = controls.get(i);
			control.update();
		}
	}

	@Override
	public void display() {
		if (!visible)
			return;

		for (int i = 0; i < controls.size(); i++) {
			Control control = controls.get(i);
			if (control.isVisible())
				control.display();
		}
	}

	@Override
	public void handleKeyEvent(KeyEvent event) {
		for (int i = 0; i < controls.size(); i++) {
			Control control = controls.get(i);
			if (control.isVisible())
				control.handleKeyEvent(event);
		}
	}

	@Override
	public void handleMouseEvent(MouseEvent event) {
		for (int i = 0; i < controls.size(); i++) {
			Control control = controls.get(i);
			if (control.isVisible())
				control.handleMouseEvent(event);
		}
	}
}
